﻿using Newtonsoft.Json;

namespace ConsoleCoreApp
{
    internal class GetImages
    {
        static int flag = 0;
        static readonly HttpClient client = new HttpClient();

        internal static async Task GetImageTask(string? url)
        {
            flag++;
            try
            {
                url = string.IsNullOrWhiteSpace(url) ? "https://api.apiopen.top/api/getImages?page=0&size=1" : url;
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    if (flag == 1)
                    {
                        response.EnsureSuccessStatusCode();
                    }
                    //else
                    //{
                    //    await GetImageTask(url);
                    //}
                    string responseBody = await response.Content.ReadAsStringAsync();
                    string? contentType = response.Content.Headers.ContentType?.ToString();

                    if (contentType != null && contentType.StartsWith("image/"))
                    {
                        // 如果是图片，下载图片
                        await DownloadImageAsync(response, "downloaded_image.jpg");
                    }
                    else if (contentType != null && contentType == "application/json; charset=utf-8")
                    {
                        // 如果是 JSON，解析 JSON 数据
                        string jsonContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(jsonContent);
                        ImgReturn? jsonObject = JsonConvert.DeserializeObject<ImgReturn>(jsonContent);
                        await Console.Out.WriteLineAsync(jsonObject?.result?.list?[0].url);
                        if (flag < 3)
                        {
                            await GetImageTask(jsonObject?.result?.list?[0].url);
                        }
                        else
                        {
                            Console.WriteLine(flag);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"未知的内容类型: {contentType}");
                    }
                }
                ;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }

        private static async Task DownloadImageAsync(HttpResponseMessage response, string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                await response.Content.CopyToAsync(fileStream);
            }
            Console.WriteLine($"图片已下载到: {fileName}");
        }
    }
}
